package logic

import (
	"context"
	"go-exp/model"
	"go-exp/pkg/errorx"
	"go-exp/query"
	"go-exp/zero/rpc/user/internal/svc"
	"go-exp/zero/rpc/user/pb/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户注册
func (l *RegisterLogic) Register(in *user.RegisterRequest) (*user.RegisterResponse, error) {
	// todo: add your logic here and delete this line
	// 查询用户名是否存在
	q := query.SysUser
	first, err2 := q.WithContext(l.ctx).Where(q.Username.Eq(in.Username)).First()
	if err2 != nil && err2.Error() != "record not found" {
		return nil, errorx.NewCodeError(500, "查询用户名失败")
	}
	if first != nil {
		return nil, errorx.MapErrorCode(errorx.USERNAME_TAKEN)
	}
	addUser := &model.SysUser{
		Username:     in.Username,
		PasswordHash: in.Password,
	}
	err := q.WithContext(l.ctx).Create(addUser)
	if err != nil {
		return nil, errorx.NewCodeError(500, "注册失败")
	}
	return &user.RegisterResponse{
		UserId: addUser.ID,
	}, nil
}
